import matplotlib.pyplot as plt
import tensorflow as tf

# ------------散点图 ---------------
# 斜率
w = 3
# Y 轴截距
b = 0
x = tf.linspace(0.0,7.0,7)
# 噪点(希望x和y的关系不是直接正相关)
noise = tf.random.normal(x.shape) + 1
y = w * (x + noise) + (b + noise)
plt.plot(x,y,'ro')

# --------------拟合线-----------------
w1 = tf.constant(2.3)
y1 = w1 * x
line, = plt.plot(x, y1, 'b-')
#---------------前向传播-----------------
for i in range(30):
    with tf.GradientTape() as tape:
        y1 = w1 * x
        # 计算方差
        # print(np.mean((y - y1)**2))
        e = tf.reduce_mean((y - y1)**2)
        slope = tape.gradient(e,x)
        print(slope)

        line.set_data(x, y1)

        w1 = w1 + 0.1

        plt.pause(1.0)

# plt.show()